package utils

import (
	"bytes"
	"fmt"
	"github.com/jordan-wright/email"
	"html/template"
	"income/model"
	"net/smtp"
	"time"
)

func GetDateFormat(timestamp int64) string {
	timeObj := time.Unix(timestamp, 0)
	year := timeObj.Year()     //年
	month := timeObj.Month()   //月
	day := timeObj.Day()       //日
	hour := timeObj.Hour()     //小时
	minute := timeObj.Minute() //分钟
	second := timeObj.Second() //秒
	return fmt.Sprintf("%04d-%02d-%02d %02d:%02d:%02d\n", year, month, day, hour, minute, second)
}

func SendEmail(to string, subject string, data []byte, isHtml bool) {
	e := email.NewEmail()
	e.From = model.SmtpPtr.From
	e.To = []string{to}
	e.Subject = subject

	if isHtml {
		e.HTML = data
	} else {
		e.Text = data
	}

	err := e.Send(model.SmtpPtr.Address, smtp.PlainAuth("",
		model.SmtpPtr.Username,
		model.SmtpPtr.Password,
		model.SmtpPtr.Host))
	if err != nil {
		Logger.Fatal(err)
	}
	Logger.Printf("邮件从%s发送到%s完成\n", e.From, e.To)
}

func Template(data interface{}) (content []byte) {
	var buff bytes.Buffer
	t1, err := template.ParseFiles("tmpl/template.html")
	if err != nil {
		panic(err)
	}

	_ = t1.Execute(&buff, data)

	content = buff.Bytes()

	return
}
